package fr.pud.server.database;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * A singleton pattern for the connection to the database
 * @author Pierre Reliquet
 */
public class Interaction {
    /**
     * The ip address of the OSM server
     */
    public static final String  IP_SERVER         = "82.67.139.156";
    /**
     * The port which gives access to the DB
     */
    public static final String  PORT_SERVER       = "5432";
    /**
     * DB's name
     */
    public static final String  DATABASE_NAME     = "osm";
    /**
     * The password which gives access to OSM DB
     */
    private static final String DATABASE_PASSWORD = "ose";
    /**
     * The user
     */
    public static final String  USER              = "serveurose";   // System.getProperty("user.name");
    /**
     * The singleton which is used for the singleton pattern
     */
    private static Connection   link;

    /**
     * @return an effective connection to the server
     */
    private static Connection connectionDatabase() {
        try {
            System.out.println("Checking driver...");
            Class.forName("org.postgresql.Driver");
            System.out.println("Driver: OK");
            System.out.println("Trying to contact the server...");
            String url = "jdbc:postgresql://" + IP_SERVER + ":" + PORT_SERVER
                    + "/" + DATABASE_NAME;
            Connection conn = DriverManager.getConnection(url, USER,
                    DATABASE_PASSWORD);
            System.out.println("Connection : OK");
            return conn;
        }
        catch (Exception e) {
            System.out.println("An error occured during server's connection!");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @return an unique instance of the DatabaseConnection
     */
    public static Connection getConnection() {
        if (link == null) {
            link = connectionDatabase();
        }
        return connectionDatabase();
    }
}
